#include "headfiles.h"

using namespace std;

static bool addSubTree(NODE *&head, int *array, int start, int end) {
	if (array == NULL) {
		cout << "Input array is NULL!" << endl;
		return false;
	}

	if (start >= end) {
		return true;
	}
	else {
		head = (NODE *)malloc(sizeof(NODE));
		if (head == NULL) {
			cout << "Allocate node error, NULL!" << endl;
			return false;
		}
		memset(head, 0, sizeof(NODE));
		int loc = (start + end) / 2;
		head->i = array[loc];
		if (start + 1 == end) {
			return true;
		}
		else {
			bool ret_code1, ret_code2;
			ret_code1 = addSubTree(head->left, array, start, loc);
			ret_code2 = addSubTree(head->right, array, loc + 1, end);
			return (ret_code1 && ret_code2);
		}
	}
}
		


NODE * createMinDepthTree(int *array, int N) {
	if (array == NULL) {
		cout << "Incorrect input array, NULL!" << endl;
		return NULL;
	}

	if (N <= 0) {
		cout << "Incorrect number of elements!" << endl;
		return NULL;
	}

	NODE *head = NULL;
	bool ret_code;
	ret_code = addSubTree(head, array, 0, N);
	if (!ret_code) {
		cout << "Create binary tree error!" << endl;
		return NULL;
	}
	
	return head;
}


